package com.example.onlinemarket.graphics;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageButton;

import com.bumptech.glide.Glide;
import com.example.onlinemarket.R;
import com.example.onlinemarket.fragment.ShoppingCartFragment;

public class ReduceButton extends AppCompatImageButton {

    private int goodId;
    private double goodPrice;
    private TextView numTv;
    private ShoppingCartFragment.OnTotalPriceChangedListener listener;

    //设置数量文本及点击监听器
    public void setNumTv(int goodId, double goodPrice, TextView numTv, ShoppingCartFragment.OnTotalPriceChangedListener listener){
        this.goodId = goodId;
        this.goodPrice = goodPrice;
        this.numTv = numTv;
        this.listener = listener;
        int num = Integer.parseInt(numTv.getText().toString());
        if(num<=0) setVisibility(INVISIBLE);
        setOnClickListener(v -> {
            int num1 = Integer.parseInt(numTv.getText().toString());
            if(num1>0){
                if(num1 == 1)
                    setVisibility(INVISIBLE);
                numTv.setText(String.valueOf(num1-1));
                listener.updateGoodNum(goodId, -1);
                listener.getTotalPrice(0-goodPrice);
            }
        });
    }

    public ReduceButton(@NonNull Context context) {
        super(context);
        setReduceImg(context);
    }

    public ReduceButton(@NonNull Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attrs) {
        super(context, attrs);
        setReduceImg(context);
    }

    public ReduceButton(@NonNull Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setReduceImg(context);
    }

    //设置图标
    private void setReduceImg(Context context){
        Glide.with(context).load(R.drawable.ic_reduce).into(this);
    }
}
